import * as api from "@/api/api";
import { isURL } from "@/utils/validate";
import RouteView from "@/components/layouts/RouteView";
import moment from "moment";
import * as dd from "dingtalk-jsapi";
import qs from 'qs'
import axios from 'axios'
import { ACCESS_TOKEN, USER_INFO, USER_NAME } from "@/store/mutation-types"
import { apiBaseUrl } from "@/utils/request";
import Vue from 'vue'
import Notice from "ant-design-vue/lib/vc-notification/Notice";
// import onlineCommons from '@jeecg/antd-online-mini'

export function timeFix() {
  const time = new Date();
  const hour = time.getHours();
  return hour < 9
    ? "早上好"
    : hour <= 11
      ? "上午好"
      : hour <= 13
        ? "中午好"
        : hour < 20
          ? "下午好"
          : "晚上好";
}
export function convertCurrency(money) {
  money = Math.abs(money);
  //汉字的数字
  var cnNums = new Array(
    "零",
    "壹",
    "贰",
    "叁",
    "肆",
    "伍",
    "陆",
    "柒",
    "捌",
    "玖"
  );
  //基本单位
  var cnIntRadice = new Array("", "拾", "佰", "仟");
  //对应整数部分扩展单位
  var cnIntUnits = new Array("", "万", "亿", "兆");
  //对应小数部分单位
  var cnDecUnits = new Array("角", "分", "毫", "厘");
  //整数金额时后面跟的字符
  var cnInteger = "整";
  //整型完以后的单位
  var cnIntLast = "元";
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = "";
  //分离金额后用的数组，预定义
  var parts;
  if (money == "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return "";
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf(".") == -1) {
    integerNum = money;
    decimalNum = "";
  } else {
    parts = money.split(".");
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != "") {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == "") {
    chineseStr += cnInteger;
  }
  return chineseStr;
}
export function welcome() {
  const arr = [
    "休息一会儿吧",
    "准备吃什么呢?",
    "要不要打一把 DOTA",
    "我猜你可能累了",
  ];
  let index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

export function convert(list) {
  //
  const map = {
    fieldShowType: "type",
    queryShowType: "type",
    fieldColumn: "nid",
    fieldName: "props.label",
    fieldDefaultValue: "initialValue",
    fieldLength: "props.maxLength",
    isShowForm: "visible",
    queryConfigFlag: "props.searchVisible",
    isShowList: "props.columnVisible", //基于isQuery为true
    isQuery: "props.query",
    // isShowForm: 'visible',
    dictTable: "props.dictTable",
    queryDictTable: "props.dictTable",
    dictField: "props.dictField",
    queryDictField: "props.dictField",
    dictText: "props.dictText",
    queryDictText: "props.dictText",
    isReadOnly: "props.readonly",
    fieldMustInput: "required",
    placeHolder: "props.placeholder",
    conditionShow: "condition",
    fieldValidType: "rules",
    isQuerySort: "props.sort",
    queryType: "props.range",
  };
  const valueConvertMap = {
    isReadOnly(v) {
      return +v === 1;
    },
    isQuerySort(v) {
      return +v === 1;
    },
    queryType(v) {
      return +v === 2;
    },
    queryConfigFlag(v) {
      return +v === 1;
    },
    isShowList(v) {
      return +v === 1;
    },
    isShowForm(v) {
      return +v === 1;
    },
    fieldMustInput(v) {
      return +v === 1;
    },
    fieldValidType(v) {
      return v ? [v] : undefined;
    },
  };
  return list.map((n) => {
    const node = {};
    for (const key in n) {
      const value = n[key];
      if (!map[key]) {
        node[key] = n[key];
        // console.log(key,'key')
        continue;
      }
      const path = map[key].split(".");
      let parent = node;
      path.forEach((p, i) => {
        if (i === path.length - 1) {
          // console.log({ p, key })
          parent[p] = valueConvertMap[key]
            ? valueConvertMap[key](value)
            : value;
        } else {
          parent[p] = parent[p] || {};
          parent = parent[p];
        }
      });
    }
    return node;
  });
}
/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  let event = document.createEvent("HTMLEvents");
  event.initEvent("resize", true, true);
  event.eventType = "message";
  window.dispatchEvent(event);
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj(obj) {
  if (!(typeof obj == "object")) {
    return;
  }

  for (let key in obj) {
    if (
      obj.hasOwnProperty(key) &&
      (obj[key] == null || obj[key] == undefined || obj[key] === "")
    ) {
      delete obj[key];
    }
  }
  return obj;
}

/**
 * 时间格式化
 * @param value
 * @param fmt
 * @returns {*}
 */
export function formatDate(value, fmt) {
  let regPos = /^\d+(\.\d+)?$/;
  if (regPos.test(value)) {
    //如果是数字
    let getDate = new Date(value);
    let o = {
      "M+": getDate.getMonth() + 1,
      "d+": getDate.getDate(),
      "h+": getDate.getHours(),
      "m+": getDate.getMinutes(),
      "s+": getDate.getSeconds(),
      "q+": Math.floor((getDate.getMonth() + 3) / 3),
      S: getDate.getMilliseconds(),
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (getDate.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
    return fmt;
  } else {
    //TODO
    value = value.trim();
    return value.substr(0, fmt.length);
  }
}

// 生成首页路由
export function generateIndexRouter(data) {
  let indexRouter = [
    {
      path: "/",
      name: "dashboard",
      component: RouteView,
      //component: () => import('@/components/layouts/BasicLayout'),
      // component: resolve => require(['@/components/layouts/TabLayout'], resolve),
      meta: { title: "首页" },
      redirect: "/dashboard/analysis",
      children: [...generateChildRouters(data)],
    },
    {
      path: "*",
      redirect: "/404",
      hidden: true,
    },
  ];
  return indexRouter;
}
const FILE_MAP = {};
const requireAll = (context) =>
  context.keys().map((path) => {
    if (!["jeecg"].some((item) => path.includes(item))) {
      const k = path
        .replace("./", "")
        .replace(".vue", "")
        .toLowerCase();
      FILE_MAP[k] = context(path);
    }
    return FILE_MAP;
  });
const context = require.context("@/", true, /\.vue$/);
// requireAll(context);
function generateChildRouters(data, appId) {
  const routers = [];
  for (let item of data) {
    let component = "";
    if (item.component.indexOf("layouts") >= 0) {
      component = "components/" + item.component;
    } else {
      component = "views/" + item.component;
    }

    // eslint-disable-next-line
    let URL = (item.meta.url || "").replace(/{{([^}}]+)?}}/g, (s1, s2) =>
      eval(s2)
    ); // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      item.meta.url = URL;
    }

    let componentPath;
    const key = "./" + component.replace("analysis", "Analysis") + ".vue";
    try {
      componentPath = context(key).default;
    } catch (e) {
      // console.log(e,{key,component},'e');
      componentPath = null;
    }
    // componentPath = require('../views/dashboard/Analysis.vue').default
    // console.log(context('@/' + component + '.vue'),'---')
    // componentPath = resolve => {
    //   const r = require(['@/views/dashboard/Analysis.vue'], (...v) => {
    //     console.log(v, 'vv')
    //   });
    //   console.log(r)
    //   return r;
    // }
    // const k = component.replace('views/','').toLowerCase();
    // console.log({FILE_MAP,k},FILE_MAP[k].default)
    // componentPath = FILE_MAP[k].default;
    // console.log(require(['@/views/dashboard/Analysis.vue']).then(console.log),'---')

    let menu = {
      path: item.path,
      name: item.name,
      redirect: item.redirect,
      key,
      component: componentPath,
      //component: resolve => require(['@/' + component+'.vue'], resolve),
      hidden: item.hidden,
      //component:()=> import(`@/views/${item.component}.vue`),
      meta: {
        appId: appId || item.id,
        routeId: item.id,
        title: item.meta.title,
        icon: item.meta.icon,
        url: item.meta.url,
        permissionList: item.meta.permissionList,
        keepAlive: item.meta.keepAlive,
        /*update_begin author:wuxianquan date:20190908 for:赋值 */
        internalOrExternal: item.meta.internalOrExternal,
        /*update_end author:wuxianquan date:20190908 for:赋值 */
        componentName: item.meta.componentName,
      },
    };
    if (item.alwaysShow) {
      menu.alwaysShow = true;
      menu.redirect = menu.path;
    }
    if (item.children && item.children.length > 0) {
      menu.children = [...generateChildRouters(item.children, menu.meta.appId)];
    }
    //--update-begin----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
    //判断是否生成路由
    if (item.route && item.route === "0") {
      //console.log(' 不生成路由 item.route：  '+item.route);
      //console.log(' 不生成路由 item.path：  '+item.path);
    } else {
      routers.push(menu);
    }
    //--update-end----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
  }

  return routers;
}

/**
 * 深度克隆对象、数组
 * @param obj 被克隆的对象
 * @return 克隆后的对象
 */
export function cloneObject(obj) {
  return JSON.parse(JSON.stringify(obj));
}

/**
 * 随机生成数字
 *
 * 示例：生成长度为 12 的随机数：randomNumber(12)
 * 示例：生成 3~23 之间的随机数：randomNumber(3, 23)
 *
 * @param1 最小值 | 长度
 * @param2 最大值
 * @return int 生成后的数字
 */
export function randomNumber() {
  // 生成 最小值 到 最大值 区间的随机数
  const random = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
  };
  if (arguments.length === 1) {
    let [length] = arguments;
    // 生成指定长度的随机数字，首位一定不是 0
    let nums = [...Array(length).keys()].map((i) =>
      i > 0 ? random(0, 9) : random(1, 9)
    );
    return parseInt(nums.join(""));
  } else if (arguments.length >= 2) {
    let [min, max] = arguments;
    return random(min, max);
  } else {
    return Number.NaN;
  }
}

/**
 * 随机生成字符串
 * @param length 字符串的长度
 * @param chats 可选字符串区间（只会生成传入的字符串中的字符）
 * @return string 生成的字符串
 */
export function randomString(length, chats) {
  if (!length) length = 1;
  if (!chats) chats = "0123456789qwertyuioplkjhgfdsazxcvbnm";
  let str = "";
  for (let i = 0; i < length; i++) {
    let num = randomNumber(0, chats.length - 1);
    str += chats[num];
  }
  return str;
}

/**
 * 随机生成uuid
 * @return string 生成的uuid
 */
export function randomUUID() {
  let chats = "0123456789abcdef";
  return randomString(32, chats);
}

/**
 * 下划线转驼峰
 * @param string
 * @returns {*}
 */
export function underLine2CamelCase(string) {
  return string.replace(/_([a-z])/g, function (all, letter) {
    return letter.toUpperCase();
  });
}

/**
 * 判断是否显示办理按钮
 * @param bpmStatus
 * @returns {*}
 */
export function showDealBtn(bpmStatus) {
  if (bpmStatus != "1" && bpmStatus != "3" && bpmStatus != "4") {
    return true;
  }
  return false;
}

/**
 * 增强CSS，可以在页面上输出全局css
 * @param css 要增强的css
 * @param id style标签的id，可以用来清除旧样式
 */
export function cssExpand(css, id) {
  let style = document.createElement("style");
  style.type = "text/css";
  style.innerHTML = `@charset "UTF-8"; ${css}`;
  // 清除旧样式
  if (id) {
    let $style = document.getElementById(id);
    if ($style != null) $style.outerHTML = "";
    style.id = id;
  }
  // 应用新样式
  document.head.appendChild(style);
}

/** 用于js增强事件，运行JS代码，可以传参 */
// options 所需参数：
//    参数名         类型            说明
//    vm             VueComponent    vue实例
//    event          Object          event对象
//    jsCode         String          待执行的js代码
//    errorMessage   String          执行出错后的提示（控制台）
export function jsExpand(options = {}) {
  // 绑定到window上的keyName
  let windowKeyName = "J_CLICK_EVENT_OPTIONS";
  if (typeof window[windowKeyName] != "object") {
    window[windowKeyName] = {};
  }

  // 随机生成JS增强的执行id，防止冲突
  let id = randomString(16, "qwertyuioplkjhgfdsazxcvbnm".toUpperCase());
  // 封装按钮点击事件
  let code = `
    (function (o_${id}) {
      try {
        (function (globalEvent, vm) {
          ${options.jsCode}
        })(o_${id}.event, o_${id}.vm)
      } catch (e) {
        o_${id}.error(e)
      }
      o_${id}.done()
    })(window['${windowKeyName}']['EVENT_${id}'])
  `;
  // 创建script标签
  const script = document.createElement("script");
  // 将需要传递的参数挂载到window对象上
  window[windowKeyName]["EVENT_" + id] = {
    vm: options.vm,
    event: options.event,
    // 当执行完成时，无论如何都会调用的回调事件
    done() {
      // 执行完后删除新增的 script 标签不会撤销执行结果（已产生的结果不会被撤销）
      script.outerHTML = "";
      delete window[windowKeyName]["EVENT_" + id];
    },
    // 当js运行出错的时候调用的事件
    error(e) {
      console.group(
        `${options.errorMessage ||
        "用户自定义JS增强代码运行出错"}（${new Date()}）`
      );
      console.error(e);
      console.groupEnd();
    },
  };
  // 将事件挂载到document中
  script.innerHTML = code;
  document.body.appendChild(script);
}

/**
 * 重复值验证工具方法
 *
 * 使用示例：
 * { validator: (rule, value, callback) => validateDuplicateValue('sys_fill_rule', 'rule_code', value, this.model.id, callback) }
 *
 * @param tableName 被验证的表名
 * @param fieldName 被验证的字段名
 * @param fieldVal 被验证的值
 * @param dataId 数据ID，可空
 * @param callback
 */
export function validateDuplicateValue(
  tableName,
  fieldName,
  fieldVal,
  dataId,
  callback
) {
  if (fieldVal) {
    let params = { tableName, fieldName, fieldVal, dataId };
    api
      .duplicateCheck(params)
      .then((res) => {
        res["success"] ? callback() : callback(res["message"]);
      })
      .catch((err) => {
        callback(err.message || err);
      });
  } else {
    callback();
  }
}

/**
 * 根据编码校验规则code，校验传入的值是否合法
 *
 * 使用示例：
 * { validator: (rule, value, callback) => validateCheckRule('common', value, callback) }
 *
 * @param ruleCode 编码校验规则 code
 * @param value 被验证的值
 * @param callback
 */
export function validateCheckRule(ruleCode, value, callback) {
  if (ruleCode && value) {
    value = encodeURIComponent(value);
    api
      .checkRuleByCode({ ruleCode, value })
      .then((res) => {
        res["success"] ? callback() : callback(res["message"]);
      })
      .catch((err) => {
        callback(err.message || err);
      });
  } else {
    callback();
  }
}

/**
 * 如果值不存在就 push 进数组，反之不处理
 * @param array 要操作的数据
 * @param value 要添加的值
 * @param key 可空，如果比较的是对象，可能存在地址不一样但值实际上是一样的情况，可以传此字段判断对象中唯一的字段，例如 id。不传则直接比较实际值
 * @returns {boolean} 成功 push 返回 true，不处理返回 false
 */
export function pushIfNotExist(array, value, key) {
  for (let item of array) {
    if (key && item[key] === value[key]) {
      return false;
    } else if (item === value) {
      return false;
    }
  }
  array.push(value);
  return true;
}

/**
 * 可用于判断是否成功
 * @type {symbol}
 */
export const succeedSymbol = Symbol();
/**
 * 可用于判断是否失败
 * @type {symbol}
 */
export const failedSymbol = Symbol();

/**
 * 使 promise 无论如何都会 resolve，除非传入的参数不是一个Promise对象或返回Promise对象的方法
 * 一般用在 Promise.all 中
 *
 * @param promise 可传Promise对象或返回Promise对象的方法
 * @returns {Promise<any>}
 */
export function alwaysResolve(promise) {
  return new Promise((resolve, reject) => {
    let p = promise;
    if (typeof promise === "function") {
      p = promise();
    }
    if (p instanceof Promise) {
      p.then((data) => {
        resolve({ type: succeedSymbol, data });
      }).catch((error) => {
        resolve({ type: failedSymbol, error });
      });
    } else {
      reject(
        "alwaysResolve: 传入的参数不是一个Promise对象或返回Promise对象的方法"
      );
    }
  });
}

/**
 * 简单实现防抖方法
 *
 * 防抖(debounce)函数在第一次触发给定的函数时，不立即执行函数，而是给出一个期限值(delay)，比如100ms。
 * 如果100ms内再次执行函数，就重新开始计时，直到计时结束后再真正执行函数。
 * 这样做的好处是如果短时间内大量触发同一事件，只会执行一次函数。
 *
 * @param fn 要防抖的函数
 * @param delay 防抖的毫秒数
 * @returns {Function}
 */
export function simpleDebounce(fn, delay = 100) {
  let timer = null;
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

/**
 * 不用正则的方式替换所有值
 * @param text 被替换的字符串
 * @param checker  替换前的内容
 * @param replacer 替换后的内容
 * @returns {String} 替换后的字符串
 */
export function replaceAll(text, checker, replacer) {
  let lastText = text;
  text = text.replace(checker, replacer);
  if (lastText !== text) {
    return replaceAll(text, checker, replacer);
  }
  return text;
}

/**
 * 获取事件冒泡路径，兼容 IE11，Edge，Chrome，Firefox，Safari
 * 目前使用的地方：JEditableTable Span模式
 */
export function getEventPath(event) {
  let target = event.target;
  let path = (event.composedPath && event.composedPath()) || event.path;

  if (path != null) {
    return path.indexOf(window) < 0 ? path.concat(window) : path;
  }

  if (target === window) {
    return [window];
  }

  let getParents = (node, memo) => {
    memo = memo || [];
    const parentNode = node.parentNode;

    if (!parentNode) {
      return memo;
    } else {
      return getParents(parentNode, memo.concat(parentNode));
    }
  };
  return [target].concat(getParents(target), window);
}

/**
 * 根据组件名获取父级
 * @param vm
 * @param name
 * @returns {Vue | null|null|Vue}
 */
export function getVmParentByName(vm, name) {
  let parent = vm.$parent;
  if (parent && parent.$options) {
    if (parent.$options.name === name) {
      return parent;
    } else {
      let res = getVmParentByName(parent, name);
      if (res) {
        return res;
      }
    }
  }
  return null;
}

/**
 * 使一个值永远不会为（null | undefined）
 *
 * @param value 要处理的值
 * @param def 默认值，如果value为（null | undefined）则返回的默认值，可不传，默认为''
 */
export function neverNull(value, def) {
  return value == null ? neverNull(def, "") : value;
}

/**
 * 根据元素值移除数组中的一个元素
 * @param array 数组
 * @param prod 属性名
 * @param value 属性值
 * @returns {string}
 */
export function removeArrayElement(array, prod, value) {
  let index = -1;
  for (let i = 0; i < array.length; i++) {
    if (array[i][prod] == value) {
      index = i;
      break;
    }
  }
  if (index >= 0) {
    array.splice(index, 1);
  }
}
export function formatUrl(url) {
  //"http:///223.240.94.226:8082///jeecg-boot//sys/common/upload" => "http://223.240.94.226:8082/jeecg-boot/sys/common/upload"
  // return url.replace(/(?<!:)\/\//gmi, '/')
}

/*数字转千分位方法 */
export function commafy(num) {
  if ((num + "").trim() == "") {
    return "";
  }
  if (isNaN(num)) {
    return "";
  }
  num = num + "";
  if (/^.*\..*$/.test(num)) {
    var pointIndex = num.lastIndexOf(".");
    var intPart = num.substring(0, pointIndex);
    var pointPart = num.substring(pointIndex + 1, num.length);
    intPart = intPart + "";
    var re = /(-?\d+)(\d{3})/;
    while (re.test(intPart)) {
      intPart = intPart.replace(re, "$1,$2");
    }
    num = intPart + "." + pointPart;
  } else {
    num = num + "";
    var re = /(-?\d+)(\d{3})/;
    while (re.test(num)) {
      num = num.replace(re, "$1,$2");
    }
  }
  return num;
}

/*数字转千分位方法带两位小数 */
export function commafyTofixed(num) {
  if ((num + "").trim() == "") {
    return "";
  }
  if (isNaN(num)) {
    return "";
  }
  num = Number(num).toFixed(2);
  num = num + "";

  if (/^.*\..*$/.test(num)) {
    var pointIndex = num.lastIndexOf(".");
    var intPart = num.substring(0, pointIndex);
    var pointPart = num.substring(pointIndex + 1, num.length);
    intPart = intPart + "";
    var re = /(-?\d+)(\d{3})/;
    while (re.test(intPart)) {
      intPart = intPart.replace(re, "$1,$2");
    }
    num = intPart + "." + pointPart;
  } else {
    num = num + "";
    var re = /(-?\d+)(\d{3})/;
    while (re.test(num)) {
      num = num.replace(re, "$1,$2");
    }
  }

  return num;
}

/*数字转千分位方法带四位小数 */
export function numberTofixed(num, float) {
  if ((num + "").trim() == "") {
    return "";
  }
  if (isNaN(num)) {
    return "";
  }
  var flo = float ? float : 4
  num = Number(num).toFixed(flo);
  num = num + "";

  if (/^.*\..*$/.test(num)) {
    var pointIndex = num.lastIndexOf(".");
    var intPart = num.substring(0, pointIndex);
    var pointPart = num.substring(pointIndex + 1, num.length);
    intPart = intPart + "";
    var re = /(-?\d+)(\d{3})/
    while (re.test(intPart)) {
      intPart = intPart.replace(re, "$1,$2")
    }
    num = intPart + "." + pointPart;
  } else {
    num = num + "";
    var re = /(-?\d+)(\d{3})/
    while (re.test(num)) {
      num = num.replace(re, "$1,$2")
    }
  }

  return num;
}
/*获取当月第一天*/
export function getMonthFirstDay(v) {
  return moment(v)
    .startOf("month")
    .format("YYYY-MM-DD");
}
/*获取当月最后一天*/
export function getMonthLastDay(v) {
  return moment(v)
    .endOf("month")
    .format("YYYY-MM-DD");
}

/*数字转化为万*/
export function numberConversion(value) {
  let num = "";
  value = String(value);
  if (value > 1 && value < 10000) {
    return value;
  } else {
    let frist_init = value.slice(0, value.length - 4); //取value后四位之外的数值，例如：32100 取3
    let last_four = value.substr(value.length - 4); //取value后四位，例如：32100 取2100
    num = `${frist_init}${last_four.slice(0, 2) === "00" ? "" : "." + last_four.slice(0, 2)
      }万`;
  }
  return num;
}

/*金额处理*/
export function clearNoNum(value,max) {
  //先把非数字的都替换掉，除了数字和.
  value = value.replace(/[^\d.]/g, "");
  //保证只有出现一个.而没有多个.
  value = value.replace(/\.{2,}/g, ".");
  //必须保证第一个为数字而不是.
  value = value.replace(/^\./g, "");
  //保证.只出现一次，而不能出现两次以上
  value = value
    .replace(".", "$#$")
    .replace(/\./g, "")
    .replace("$#$", ".");
  //只能输入四个小数
  value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
  // console.log(value.includes('.'),'wwwwww')
  //小数位处理
  if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
    value = "0";
  }
  //输入长度控制
  if (value > 999999999999.9999) {
    value = 999999999999.9999;
  }

  if (value > max) {
    value = max
  }

  return value;
}
/*判断是否具有按钮权限 */
export function GetBtnpermissions(v) {
  return JSON.parse(sessionStorage.getItem("LOGIN_USER_BUTTON_AUTH")).some(
    (item) => item.action == v
  );
}

/*设置标题*/
export function setTitle(v) {
  dd.biz.navigation.setTitle({
    title: v, //控制标题文本，空字符串表示显示默认文本
    onSuccess: function (result) { },
    onFail: function (err) { },
  });
}

/*弹窗赋值*/

export function setToggleVal(that, key, val) {
  that.$store.commit("SET_TOGGLE", {
    key: key,
    value: val,
  });
}

/* 判断机型 */
export function appSource() {
  const u = navigator.userAgent;
  const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isiOS) {
    return "ios";
  } else {
    return "andriod";
  }
}

/* 银行卡号校验 仅允许数字和空格 */
export function clearAccount(value) {
  value = value.replace(/[^\d ]/g, "");
  return value;
}
// 加法
export function accAdd(arg1, arg2) {
  var r1, r2, m, c;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  c = Math.abs(r1 - r2);
  m = Math.pow(10, Math.max(r1, r2));
  if (c > 0) {
    var cm = Math.pow(10, c);
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", "")) * cm;
    } else {
      arg1 = Number(arg1.toString().replace(".", "")) * cm;
      arg2 = Number(arg2.toString().replace(".", ""));
    }
  } else {
    arg1 = Number(arg1.toString().replace(".", ""));
    arg2 = Number(arg2.toString().replace(".", ""));
  }
  return (arg1 + arg2) / m;
}
// 减法
export function accSub(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
// 乘法
export function accMul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) { }
  try {
    m += s2.split(".")[1].length;
  } catch (e) { }

  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  );
}
// 乘法/保留4位小数
export function accMulMin(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) { }
  try {
    m += s2.split(".")[1].length;
  } catch (e) { }
  let value = (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  )
  value = value.toString().replace(/^(\-)*(\d+)\.(\d{4}).*$/, '$1$2.$3')
  return value;
}
// 除法
export function accDiv(arg1, arg2) {
  var t1 = 0,
    t2 = 0,
    r1,
    r2;
  try {
    t1 = arg1.toString().split(".")[1].length;
  } catch (e) { }
  try {
    t2 = arg2.toString().split(".")[1].length;
  } catch (e) { }

  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));

  return (r1 / r2) * Math.pow(10, t2 - t1);
}
// 除法/保留4位小数
export function accDivMin(arg1, arg2) {
  var t1 = 0,
    t2 = 0,
    r1,
    r2,
    value
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) { }
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) { }

  r1 = Number(arg1.toString().replace('.', ''))
  r2 = Number(arg2.toString().replace('.', ''))
  value = (r1 / r2) * Math.pow(10, t2 - t1)
  value = value.toString().replace(/^(\-)*(\d+)\.(\d{4}).*$/, '$1$2.$3')
  return value
}

//比较时间大小
export function compareDate(date1, date2) {
  var oDate1 = new Date(date1)
  var oDate2 = new Date(date2)
  if (oDate1.getTime() > oDate2.getTime()) {
    return true //第一个大
  } else {
    return false //第二个大
  }
}

/*数字转千分位方法不带两位小数 */
export function numFormat(num) {
  if ((num + "").trim() == "") {
    return "";
  }
  if (isNaN(num)) {
    return "";
  }
  num = Number(num);
  num = num + "";

  if (/^.*\..*$/.test(num)) {
    var pointIndex = num.lastIndexOf(".");
    var intPart = num.substring(0, pointIndex);
    var pointPart = num.substring(pointIndex + 1, num.length);
    intPart = intPart + "";
    var re = /(-?\d+)(\d{3})/
    while (re.test(intPart)) {
      intPart = intPart.replace(re, "$1,$2")
    }
    num = intPart + "." + pointPart;
  } else {
    num = num + "";
    var re = /(-?\d+)(\d{3})/
    while (re.test(num)) {
      num = num.replace(re, "$1,$2")
    }
  }

  return num;
}
